﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFSoft.UBF.Business;
using UFSoft.UBF.Eventing;
using UFIDA.U9.PM.Rcv;
using UFIDA.U9.PM.Verification;

namespace UFIDA.U9.Cust.LS.PlugBE
{
    class JHNReceivementZWZExtend : IEventSubscriber
    {

        public void Notify(params object[] args)
        {
            if (args != null && args.Length != 0 && args[0] is EntityEvent)
            {
                BusinessEntity.EntityKey key = ((EntityEvent)args[0]).EntityKey;
                Receivement receivement = key.GetEntity() as Receivement;//委外收货
                if (receivement == null)
                    return;

                if (receivement.Status == UFIDA.U9.PM.Rcv.RcvStatusEnum.InStoreConfirmed //当前状态是入库确认
                    && receivement.OriginalData.Status == UFIDA.U9.PM.Rcv.RcvStatusEnum.Approving) //之前的状态是审核中
                {
                    /**
                     收益率 = 委外收货数量/该委外收货行对应核销单行已核销数量
                     委外收货--> 来源单据、来源单据行 --> 找到对应的核销单行-->取累计核销数量
                     */
                    foreach (RcvLine line in receivement.RcvLines)
                    {
                        //每一行都有收益率需要计算，用来源单据、来源单据行找到核销单行的已核销数量
                        //取核销单
                        PM.Verification.VerificationLine VLine
                            = PM.Verification.VerificationLine.Finder
                            .Find($"DocNo='{receivement.DocNo}' and DocLineNo = {line.DocLineNo}");


                        if (VLine == null || VLine.VerificationShipline == null) continue;
                        decimal hxsl = 0;
                        foreach (VerificationShipline vsl in VLine.VerificationShipline)
                        {
                            hxsl += vsl.VerificationAvailableQtyIU;
                        }
                        //本次收货数量/本次核销数量
                        decimal syl = hxsl == 0 ? 0 : line.RcvQtyTU / hxsl;
                        // 写入
                        using (ISession session = Session.Open())
                        {
                            line.DescFlexSegments.PrivateDescSeg7 = syl.ToString();
                            session.Commit();
                        }
                    }
                }
            }
        
            
        }
    }
}
